package com.chen.ui;

import com.chen.cache.PrivateMessageCache;
import com.chen.entry.PrivateMessage;
import com.chen.infa.PrivateChatMessageListener;
import com.chen.util.AppContext;
import com.chen.util.Constant;
import com.chen.util.MssageStringUtils;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.DataOutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PrivateChatWindow extends JFrame {

    private JTextArea chatArea;
    private JTextField inputField;
    private final String selectedUser;
    private static final Map<String, PrivateChatWindow> openPanels = new HashMap<>();

    private PrivateChatMessageListener listener;

    public PrivateChatWindow(String selectedUser) {
        setTitle("私聊 - " + selectedUser);
        this.selectedUser = selectedUser;
        initView();
        setVisible(true);
        openPanels.put(this.selectedUser, this);
    }

    public static boolean isOpenFor(String user) {
        return openPanels.containsKey(user);
    }

    private void initView() {
        setSize(400, 300);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setLocationRelativeTo(null);
        setLayout(new BorderLayout());

        // 聊天显示区域
        chatArea = new JTextArea();
        chatArea.setEditable(false);
        JScrollPane chatScrollPane = new JScrollPane(chatArea);
        add(chatScrollPane, BorderLayout.CENTER);

        // 输入区域
        JPanel inputPanel = new JPanel(new BorderLayout());
        inputField = new JTextField();
        JButton sendButton = new JButton("发送");

        sendButton.addActionListener(this::sendMessage);

        inputField.addActionListener(this::sendMessage);

        inputPanel.add(inputField, BorderLayout.CENTER);
        inputPanel.add(sendButton, BorderLayout.EAST);

        add(inputPanel, BorderLayout.SOUTH);
        // 加载历史未读消息
        List<PrivateMessage> unread = PrivateMessageCache.getInstance().getAndClearUnreadMessages(selectedUser);
        for (PrivateMessage msg : unread) {
            chatArea.append(msg + "\n");
        }
    }

    private void sendMessage(ActionEvent e) {
        try {
            String message = inputField.getText().trim();
            inputField.setText("");
            if (!message.isEmpty()) {
                // 首先，自己就不需要，接收来自自己的消息，直接将消息展示到聊天框
                chatArea.append(MssageStringUtils.getMsgStr(message, AppContext.getInstance().getUsername()) + "\r\n");
                // 获取通信管道的输出流
                DataOutputStream out = new DataOutputStream(AppContext.getInstance().getClientSocket().getOutputStream());
                // 向服务端发送消息，要先标志这次的消息类型是私聊消息
                out.writeUTF(Constant.PERSONAL_MSG);
                // 出现错误，问题是，服务端拿不到私聊对象的用户名
                // 所以要将用户名写入到服务端
                out.writeUTF(selectedUser);
                // 再发送消息本体
                out.writeUTF(message);
                // 刷新管道
                out.flush();
            }
        } catch (Exception ex) {
            System.out.println("客户端私聊消息发送失败");
            ex.printStackTrace();
        }
    }

    public void showMsgToPersonal(String fromUser, String msg) {
        PrivateChatWindow panel = openPanels.get(fromUser);
        if (panel != null) {
            chatArea.append(msg + "\r\n");
        }

    }
}